import { Controller, Headers, Post, Body, HttpCode, UseGuards, Get, Query } from '@nestjs/common';
import { UserService } from './user.service';
import { LoginDto, RegisterUserDto } from './dto/user.dto';
import { ApiQuery, ApiBody, ApiOperation, ApiResponse, ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { UserEntity } from 'src/modules/admin/user/entities/user.entity';
import { throwHttp } from 'src/utlis';
import { AuthGuard } from '@nestjs/passport';
import { TokenDto } from 'src/common/auth/constants';
import { UpdateUserInfoDto } from 'src/modules/admin/user/dto/user.dto';
import { isTrue } from 'src/utlis/tools';
import { JwtService } from '@nestjs/jwt';
@ApiBearerAuth() // swagger文档设置token
@ApiTags('用户')
@Controller('home/user')
export class UserController {
  constructor(private readonly userService: UserService, private readonly jwtService: JwtService,) { }

  @HttpCode(200)
  @Post('/registerUser')
  @ApiBody({ description: '用户注册', type: RegisterUserDto })
  @ApiOperation({ summary: '用户注册', operationId: 'registerUser' })
  @ApiResponse({ status: 200, type: UserEntity })
  registerUser(@Body() body: RegisterUserDto) {
    return this.userService.registerUser(body);
  }
  @HttpCode(200)
  @Post('/login')
  @ApiBody({ description: '登录', type: LoginDto })
  @ApiOperation({ summary: '登录', operationId: 'login' })
  login(@Body() body: LoginDto) {
    try {
      return this.userService.login(body);
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 修改用户信息 */
  @HttpCode(200)
  @Post('/updateUserInfo')
  @ApiBody({ description: '修改用户信息', type: UpdateUserInfoDto })
  @ApiOperation({ summary: '修改用户信息', operationId: 'updateUserInfo' })
  @UseGuards(AuthGuard('userJwt'))
  @ApiResponse({ status: 200, type: String })
  updateUserInfo(@Body() body: UpdateUserInfoDto, @Headers('authorization') authorization) {
    if (!isTrue(authorization)) {
      throwHttp('获取token失败');
    }
    const token = authorization.split(' ');
    const user: TokenDto = this.jwtService.decode(token[1]) as TokenDto;
    return this.userService.updateUserInfo(body, user.userId);
  }
  /** 用户详情 */
  @HttpCode(200)
  @Get('/getUserInfo')
  @ApiResponse({
    status: 200,
    description: '用户详情',
    type: UserEntity,
  })
  @ApiOperation({
    tags: ['获取用户详情'],
    summary: '获取用户详情',
    operationId: 'getUserInfo',
  })
  @UseGuards(AuthGuard('userJwt'))
  async getUserInfo(@Headers('Authorization') authorization) {
    if (!isTrue(authorization)) {
      throwHttp('获取token失败');
    }
    const token = authorization.split(' ');
    const user: TokenDto = this.jwtService.decode(token[1]) as TokenDto;
    const data = await this.userService.getUserInfo(user.userId);
    return data;
  }
}
